﻿namespace SampleApplication.CoffeeShopSample.Implementation.Application.CommandsParsers
{
    #region Usings

    using Commands;
    using Dependencies.Application;
    using Domain;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    #endregion Usings

    public class CommandParser : ICommandParser
    {
        private readonly IOutputWriter outputWriter;
        private readonly IList<ICommandParser> commandParsers;

        public CommandParser(IOutputWriter outputWriter, IEnumerable<ICommandParser> commandParsers)
        {
            if (outputWriter == null) throw new ArgumentNullException("outputWriter");
            if (commandParsers == null) throw new ArgumentNullException("commandParsers");

            this.outputWriter = outputWriter;
            this.commandParsers = commandParsers.ToList();
        }

        public ICommand Parse(string commandValue)
        {
            if (string.IsNullOrWhiteSpace(commandValue)) return new NotRecognizedCommand(outputWriter);

            foreach (var commandParser in commandParsers)
            {
                var command = commandParser.Parse(commandValue);

                if (command != null) return command;
            }

            return new NotRecognizedCommand(outputWriter);
        }
    }
}